using FirstTea.Application.DTOs;
using FirstTea.Application.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace FirstTea.Api.Controllers
{
                [ApiController]
                [Route("api/[controller]")]
                public class UserController : ControllerBase
                {
                    private readonly IUserService _userService;
                    private readonly IAuthService _authService;
                    public UserController(IUserService userService, IAuthService authService)
                    {
                        _userService = userService;
                        _authService = authService;
                    }

                    /// <summary>
                    /// 用户头像上传（需登录）
                    /// </summary>
                    [HttpPost("upload-avatar")]
                    [Authorize]
                    public async Task<IActionResult> UploadAvatar([FromForm] IFormFile avatar)
                    {
                        try
                        {
                            if (avatar == null || avatar.Length == 0)
                                return BadRequest(new { message = "请选择图片文件" });
                            var userId = User.FindFirst("sub")?.Value;
                            if (string.IsNullOrEmpty(userId)) return Unauthorized();
                            var ext = System.IO.Path.GetExtension(avatar.FileName);
                            var fileName = $"avatar_{userId}_{DateTime.Now.Ticks}{ext}";
                            var savePath = System.IO.Path.Combine("wwwroot", "uploads", fileName);
                            using (var stream = System.IO.File.Create(savePath))
                            {
                                await avatar.CopyToAsync(stream);
                            }
                            // 更新数据库用户头像路径
                            await _userService.UpdateAvatarAsync(Guid.Parse(userId), $"/uploads/{fileName}");
                            return Ok(new { url = $"/uploads/{fileName}" });
                        }
                        catch (Exception ex)
                        {
                            return StatusCode(500, new { message = "头像上传失败", detail = ex.Message });
                        }
                    }

        /// <summary>
        /// 获取用户信息（需登录）
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        public async Task<ActionResult<UserDto?>> GetById(Guid id)
        {
            try
            {
                var user = await _userService.GetByIdAsync(id);
                if (user == null) return NotFound(new { message = "用户不存在" });
                user.Password = null;
                return Ok(user);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "服务器内部错误", detail = ex.Message });
            }
        }

        /// <summary>
        /// 用户注册（匿名访问）
        /// </summary>
        [HttpPost("register")]
        [AllowAnonymous]
        public async Task<ActionResult<AuthResponseDto>> Register([FromBody] UserDto dto)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                var result = await _authService.RegisterAsync(dto.Username ?? "", dto.Email ?? "", dto.Password ?? "");
                if (string.IsNullOrEmpty(result.Token)) return BadRequest(new { message = result.Message });
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "注册失败", detail = ex.Message });
            }
        }

        /// <summary>
        /// 用户登录（匿名访问）
        /// </summary>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<ActionResult<AuthResponseDto>> Login([FromBody] UserDto dto)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                var result = await _authService.LoginAsync(dto.Username ?? "", dto.Password ?? "");
                if (string.IsNullOrEmpty(result.Token)) return Unauthorized(new { message = result.Message });
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "登录失败", detail = ex.Message });
            }
        }

        /// <summary>
        /// 修改用户信息（需登录）
        /// </summary>
        [HttpPut("update")]
        [Authorize]
        public async Task<IActionResult> Update([FromBody] UserDto dto)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                await _userService.UpdateAsync(dto);
                return Ok(new { message = "用户信息已更新" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "更新失败", detail = ex.Message });
            }
        }

        /// <summary>
        /// 删除用户（需登录）
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        public async Task<IActionResult> Delete(Guid id)
        {
            try
            {
                await _userService.DeleteAsync(id);
                return Ok(new { message = "用户已删除" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "删除失败", detail = ex.Message });
            }
        }

        /// <summary>
        /// 获取所有用户（需管理员权限）
        /// </summary>
        [HttpGet("all")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<IEnumerable<UserDto>>> GetAll()
        {
            try
            {
                var users = await _userService.GetAllAsync();
                foreach (var user in users) user.Password = null;
                return Ok(users);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取用户列表失败", detail = ex.Message });
            }
        }

        /// <summary>
        /// 密码重置（需登录）
        /// </summary>
        [HttpPost("reset-password")]
        [Authorize]
        public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordDto dto)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                await _userService.ResetPasswordAsync(dto.UserId, dto.NewPassword);
                return Ok(new { message = "密码已重置" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "密码重置失败", detail = ex.Message });
            }
        }
    }
}
